package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;



    /**
     * 获取登录验证码
     *   请求参数：phone （Map）
     *   响应：void
     * ResponseEntity
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        ErrorResult errorResult = null;
        String phone =(String) map.get("phone");
        try {
            errorResult = userService.sendMsg(phone);
            if (null == errorResult) {
                return ResponseEntity.ok(null);
            }
        } catch (BusinessException e) {
            log.error("发送短信验证码失败~ phone = " + phone, e);
            errorResult = ErrorResult.fail();
        } catch (Exception e) {
            errorResult = ErrorResult.error();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 检验登录
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map) {
        //1、调用map集合获取请求参数
        String phone = (String) map.get("phone");
        String code = (String) map.get("verificationCode");
        //2、调用userService完成用户登录
        Map retMap = userService.loginVerification(phone,code);
        //3、构造返回
        return ResponseEntity.ok(retMap);
    }


    /**
     * 保存用户信息
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo) {
        //2、向userinfo中设置用户id
        userInfo.setId(UserHolder.getUserId());
        //3、调用service
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }

    @PostMapping("/loginReginfo/head")
    public ResponseEntity<ErrorResult> loginReginfoHead(MultipartFile headPhoto){
        //3、调用service
        try {
            userInfoService.updateHead(headPhoto,UserHolder.getUserId());
        } catch (BusinessException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.faceError());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResult.error());
        }
        return ResponseEntity.ok(null);
    }

}
